<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
    
  
  <link href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="https://cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.css" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.0.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="mask-icon" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0" color="#222">





  <meta name="keywords" content="vps, java, python, golang, springmvc">




  


  <link rel="alternate" href="/atom.xml" title="张恒的网络日志" type="application/atom+xml">






<meta name="keywords" content="java, python, go, 技术, 学习笔记, spring">
<meta property="og:type" content="website">
<meta property="og:title" content="张恒的网络日志">
<meta property="og:url" content="http://blog.gavinzh.com/404.html">
<meta property="og:site_name" content="张恒的网络日志">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-01-05T08:52:36.912Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="张恒的网络日志">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: true,
    lazyload: true,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.gavinzh.com/404.html">





  <title>SpringMVC 解毒4 | 张恒的网络日志</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-98061925-1', 'auto');
  ga('send', 'pageview');
</script>





</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">张恒的网络日志</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Zhang Heng's WebSite Blog</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-4/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gavin Zhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/5567916">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="张恒的网络日志">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">SpringMVC 解毒4</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-12T08:40:00+00:00">2018-08-12</time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/笔记/" itemprop="url" rel="index">
                    <span itemprop="name">笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/08/12/learn-springmvc-code-4/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/08/12/learn-springmvc-code-4/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2018/08/12/learn-springmvc-code-4/" class="leancloud_visitors" data-flag-title="SpringMVC 解毒4">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="5-ViewResolver"><a href="#5-ViewResolver" class="headerlink" title="5 ViewResolver"></a>5 ViewResolver</h2><img src="http://www.plantuml.com/plantuml/svg/dLHTJy8m57tVh-WZHDmVa6Y4Q3G17W29hvVjCXQwjhQN8L7-krqt8fDHm3wqNS-vvtvr3HH4AqYGIPs4HkbK90iD6MwaNeKRd8S6TSwHs5SGC3jIGQWN426RfRWPev4yHsrHLeqR1p1T8iL-PELQ4ogaMLvzTzX0Hi2HSRUq6Isrt1Zsz1cXebIAEolbD7TkRl1Tyrd99qXzQLc2fbk5hVO18vTfRACICUhM45ItjEYmXtkMoHXvXxqGgKcPxHW_rcZ8yjtw1pDA2eD5Ycvp77mL-2u8Bgnkc9S9ESE8Wp6iXo2AIXsM-RSK9QVATOI9f1J8gllOXrXVPagQbB1q2ND36Y9YZzMc3z7oZDnxndtmc-OzC1ZxE7jlKymK1_Bc-beqNm0lyBMElDmzfxSMCJ_1T5Fj3dU_Rs_FbFsOVsaBZYsRs-4nkAWt7bAfuk_BMVEJNJzhUKbJceAh9--_AgVjlTVdoXyrN6Z43FJAFNm7z-xPdW_TkRz6JKcKOPvGk3h27Et3cjAs7j-iElM-4XLd05kvfl_cuVVKXDRj6hpR6lm0">

<a id="more"></a>

<p>ViewResolver 视图解析器能够通过viewName视图名和locale用户区域获取View对象，从而渲染视图。 如果你想使用自定义的一个模板引擎，就得配置上相对应的ViewResolver。</p>
<h3 id="5-1-BeanNameViewResolver-分析"><a href="#5-1-BeanNameViewResolver-分析" class="headerlink" title="5.1 BeanNameViewResolver 分析"></a>5.1 BeanNameViewResolver 分析</h3><p>我们还是从最简单的讲起，给你一个最初的印象。BeanNameViewResolver 可谓是真的简单，它会根据viewName从web应用上下文中获取到实现View接口的bean并返回，web应用上下文从哪来？当然是继承相应的接口，被web应用上下文在初始化时注入。</p>
<p>直接看代码即可：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> View <span class="title">resolveViewName</span><span class="params">(String viewName, Locale locale)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">    ApplicationContext context = getApplicationContext();</span><br><span class="line">    <span class="keyword">if</span> (!context.containsBean(viewName)) &#123;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"No matching bean found for view name '"</span> + viewName + <span class="string">"'"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// Allow for ViewResolver chaining...</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (!context.isTypeMatch(viewName, View<span class="class">.<span class="keyword">class</span>)) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Found matching bean for view name '"</span> + viewName +</span><br><span class="line">                    <span class="string">"' - to be ignored since it does not implement View"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// Since we're looking into the general ApplicationContext here,</span></span><br><span class="line">        <span class="comment">// let's accept this as a non-match and allow for chaining as well...</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> context.getBean(viewName, View<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-2-ViewResolverComposite-分析"><a href="#5-2-ViewResolverComposite-分析" class="headerlink" title="5.2 ViewResolverComposite 分析"></a>5.2 ViewResolverComposite 分析</h3><p>凡是以Composite结尾的类，都是包含一组实现类，由其挑选合适的实现类并执行。ViewResolverComposite 也不例外。</p>
<p>代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> View <span class="title">resolveViewName</span><span class="params">(String viewName, Locale locale)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (ViewResolver viewResolver : <span class="keyword">this</span>.viewResolvers) &#123;</span><br><span class="line">        View view = viewResolver.resolveViewName(viewName, locale);</span><br><span class="line">        <span class="keyword">if</span> (view != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> view;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-3-ContentNegotiatingViewResolver-分析"><a href="#5-3-ContentNegotiatingViewResolver-分析" class="headerlink" title="5.3 ContentNegotiatingViewResolver 分析"></a>5.3 ContentNegotiatingViewResolver 分析</h3><p>ContentNegotiatingViewResolver 比 ViewResolverComposite 高级一点，高级在可以通过 MediaType 来筛选出更加合适的View。</p>
<h4 id="5-3-1-ContentNegotiatingViewResolver-初始化分析"><a href="#5-3-1-ContentNegotiatingViewResolver-初始化分析" class="headerlink" title="5.3.1 ContentNegotiatingViewResolver 初始化分析"></a>5.3.1 ContentNegotiatingViewResolver 初始化分析</h4><p>ContentNegotiatingViewResolver 是一个带有初始化的类，在初始化中，它会把web应用上下文和父上下文中所有的 ViewResolver 实现类bean加载到自己的属性viewResolvers中，当然，开发者也可以在xml配置中向viewResolvers属性注入bean。同时 ContentNegotiatingViewResolver 还有一个 defaultViews属性，用于存放一组默认的View实现类bean，这个是需要xml配置的。</p>
<p>代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initServletContext</span><span class="params">(ServletContext servletContext)</span> </span>&#123;</span><br><span class="line">    Collection&lt;ViewResolver&gt; matchingBeans =</span><br><span class="line">            BeanFactoryUtils.beansOfTypeIncludingAncestors(getApplicationContext(), ViewResolver<span class="class">.<span class="keyword">class</span>).<span class="title">values</span>()</span>;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.viewResolvers == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.viewResolvers = <span class="keyword">new</span> ArrayList&lt;ViewResolver&gt;(matchingBeans.size());</span><br><span class="line">        <span class="keyword">for</span> (ViewResolver viewResolver : matchingBeans) &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span> != viewResolver) &#123;</span><br><span class="line">                <span class="keyword">this</span>.viewResolvers.add(viewResolver);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; viewResolvers.size(); i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (matchingBeans.contains(viewResolvers.get(i))) &#123;</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            String name = viewResolvers.get(i).getClass().getName() + i;</span><br><span class="line">            getApplicationContext().getAutowireCapableBeanFactory().initializeBean(viewResolvers.get(i), name);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.viewResolvers.isEmpty()) &#123;</span><br><span class="line">        logger.warn(<span class="string">"Did not find any ViewResolvers to delegate to; please configure them using the "</span> +</span><br><span class="line">                <span class="string">"'viewResolvers' property on the ContentNegotiatingViewResolver"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    AnnotationAwareOrderComparator.sort(<span class="keyword">this</span>.viewResolvers);</span><br><span class="line">    <span class="keyword">this</span>.cnmFactoryBean.setServletContext(servletContext);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-3-2-ContentNegotiatingViewResolver-处理请求分析"><a href="#5-3-2-ContentNegotiatingViewResolver-处理请求分析" class="headerlink" title="5.3.2 ContentNegotiatingViewResolver 处理请求分析"></a>5.3.2 ContentNegotiatingViewResolver 处理请求分析</h3><p>在前面，我们说了它会通过MediaType来筛选出更合适的View，怎么筛选的呢？来看代码吧</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> View <span class="title">resolveViewName</span><span class="params">(String viewName, Locale locale)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    RequestAttributes attrs = RequestContextHolder.getRequestAttributes();</span><br><span class="line">    Assert.isInstanceOf(ServletRequestAttributes<span class="class">.<span class="keyword">class</span>, <span class="title">attrs</span>)</span>;</span><br><span class="line">    List&lt;MediaType&gt; requestedMediaTypes = getMediaTypes(((ServletRequestAttributes) attrs).getRequest());</span><br><span class="line">    <span class="keyword">if</span> (requestedMediaTypes != <span class="keyword">null</span>) &#123;</span><br><span class="line">        List&lt;View&gt; candidateViews = getCandidateViews(viewName, locale, requestedMediaTypes);</span><br><span class="line">        View bestView = getBestView(candidateViews, requestedMediaTypes, attrs);</span><br><span class="line">        <span class="keyword">if</span> (bestView != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> bestView;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.useNotAcceptableStatusCode) &#123;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"No acceptable view found; returning 406 (Not Acceptable) status code"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> NOT_ACCEPTABLE_VIEW;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        logger.debug(<span class="string">"No acceptable view found; returning null"</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> List&lt;View&gt; <span class="title">getCandidateViews</span><span class="params">(String viewName, Locale locale, List&lt;MediaType&gt; requestedMediaTypes)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    List&lt;View&gt; candidateViews = <span class="keyword">new</span> ArrayList&lt;View&gt;();</span><br><span class="line">    <span class="keyword">for</span> (ViewResolver viewResolver : <span class="keyword">this</span>.viewResolvers) &#123;</span><br><span class="line">        View view = viewResolver.resolveViewName(viewName, locale);</span><br><span class="line">        <span class="keyword">if</span> (view != <span class="keyword">null</span>) &#123;</span><br><span class="line">            candidateViews.add(view);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span> (MediaType requestedMediaType : requestedMediaTypes) &#123;</span><br><span class="line">            List&lt;String&gt; extensions = <span class="keyword">this</span>.contentNegotiationManager.resolveFileExtensions(requestedMediaType);</span><br><span class="line">            <span class="keyword">for</span> (String extension : extensions) &#123;</span><br><span class="line">                String viewNameWithExtension = viewName + <span class="string">"."</span> + extension;</span><br><span class="line">                view = viewResolver.resolveViewName(viewNameWithExtension, locale);</span><br><span class="line">                <span class="keyword">if</span> (view != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    candidateViews.add(view);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (!CollectionUtils.isEmpty(<span class="keyword">this</span>.defaultViews)) &#123;</span><br><span class="line">        candidateViews.addAll(<span class="keyword">this</span>.defaultViews);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> candidateViews;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> View <span class="title">getBestView</span><span class="params">(List&lt;View&gt; candidateViews, List&lt;MediaType&gt; requestedMediaTypes, RequestAttributes attrs)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (View candidateView : candidateViews) &#123;</span><br><span class="line">        <span class="keyword">if</span> (candidateView <span class="keyword">instanceof</span> SmartView) &#123;</span><br><span class="line">            SmartView smartView = (SmartView) candidateView;</span><br><span class="line">            <span class="keyword">if</span> (smartView.isRedirectView()) &#123;</span><br><span class="line">                <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">                    logger.debug(<span class="string">"Returning redirect view ["</span> + candidateView + <span class="string">"]"</span>);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">return</span> candidateView;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (MediaType mediaType : requestedMediaTypes) &#123;</span><br><span class="line">        <span class="keyword">for</span> (View candidateView : candidateViews) &#123;</span><br><span class="line">            <span class="keyword">if</span> (StringUtils.hasText(candidateView.getContentType())) &#123;</span><br><span class="line">                MediaType candidateContentType = MediaType.parseMediaType(candidateView.getContentType());</span><br><span class="line">                <span class="keyword">if</span> (mediaType.isCompatibleWith(candidateContentType)) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">                        logger.debug(<span class="string">"Returning ["</span> + candidateView + <span class="string">"] based on requested media type '"</span> +</span><br><span class="line">                                mediaType + <span class="string">"'"</span>);</span><br><span class="line">                    &#125;</span><br><span class="line">                    attrs.setAttribute(View.SELECTED_CONTENT_TYPE, mediaType, RequestAttributes.SCOPE_REQUEST);</span><br><span class="line">                    <span class="keyword">return</span> candidateView;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>代码第5行首先会获取request可接受的并且服务器支持的MediaType，如果没有且配置该bean的时候属性useNotAcceptableStatusCode设置为true，会返回Http状态码为406的结果，否则，返回null，让别的resolver再去处理，属性useNotAcceptableStatusCode默认为false。</p>
<p>代码第7行会调用getCandidateViews方法获取所有返回的View。实际上，除了根据viewName获取View外，还会给viewName加上一些后缀名再去获取。最后，如果defaultViews如果不为空，还会获取defaultViews中的View。</p>
<p>代码第8行调用getBestView方法挑选出从第7行获取的所有View。如何挑选？首先判断有没有重定向，如果有重定向，则返回重定向的view，否则从每一个view中获取ContentType，如果ContentType可以满足request的需求，则返回该view。</p>
<h3 id="5-4-AbstractCachingViewResolver-分析"><a href="#5-4-AbstractCachingViewResolver-分析" class="headerlink" title="5.4 AbstractCachingViewResolver 分析"></a>5.4 AbstractCachingViewResolver 分析</h3><p>以上三种 ViewResolver 实现类基本上都是从web应用上下文获取View 或者在调用别的 ViewResolver。而接下来的类则会是我们经常用到的。</p>
<p>AbstractCachingViewResolver 顾名思义，就是带缓存的 ViewResolver，它利用了LinkedHashMap中的一个方法，就是在添加K-V时，会判断要不要删除最早加入的K-V，所以这个类实现的是FIFO类型的缓存，默认缓存数量是1024个。</p>
<p>接下来简单看看代码吧</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** Default maximum number of entries for the view cache: 1024 */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> DEFAULT_CACHE_LIMIT = <span class="number">1024</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** The maximum number of entries in the cache */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">int</span> cacheLimit = DEFAULT_CACHE_LIMIT;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** Whether we should refrain from resolving views again if unresolved once */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">boolean</span> cacheUnresolved = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** Fast access cache for Views, returning already cached instances without a global lock */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Map&lt;Object, View&gt; viewAccessCache = <span class="keyword">new</span> ConcurrentHashMap&lt;Object, View&gt;(DEFAULT_CACHE_LIMIT);</span><br><span class="line"></span><br><span class="line"><span class="comment">/** Map from view key to View instance, synchronized for View creation */</span></span><br><span class="line"><span class="meta">@SuppressWarnings</span>(<span class="string">"serial"</span>)</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Map&lt;Object, View&gt; viewCreationCache =</span><br><span class="line">        <span class="keyword">new</span> LinkedHashMap&lt;Object, View&gt;(DEFAULT_CACHE_LIMIT, <span class="number">0.75f</span>, <span class="keyword">true</span>) &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">removeEldestEntry</span><span class="params">(Map.Entry&lt;Object, View&gt; eldest)</span> </span>&#123;</span><br><span class="line">                <span class="keyword">if</span> (size() &gt; getCacheLimit()) &#123;</span><br><span class="line">                    viewAccessCache.remove(eldest.getKey());</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> View <span class="title">resolveViewName</span><span class="params">(String viewName, Locale locale)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!isCache()) &#123;</span><br><span class="line">        <span class="keyword">return</span> createView(viewName, locale);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        Object cacheKey = getCacheKey(viewName, locale);</span><br><span class="line">        View view = <span class="keyword">this</span>.viewAccessCache.get(cacheKey);</span><br><span class="line">        <span class="keyword">if</span> (view == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (<span class="keyword">this</span>.viewCreationCache) &#123;</span><br><span class="line">                view = <span class="keyword">this</span>.viewCreationCache.get(cacheKey);</span><br><span class="line">                <span class="keyword">if</span> (view == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="comment">// Ask the subclass to create the View object.</span></span><br><span class="line">                    view = createView(viewName, locale);</span><br><span class="line">                    <span class="keyword">if</span> (view == <span class="keyword">null</span> &amp;&amp; <span class="keyword">this</span>.cacheUnresolved) &#123;</span><br><span class="line">                        view = UNRESOLVED_VIEW;</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">if</span> (view != <span class="keyword">null</span>) &#123;</span><br><span class="line">                        <span class="keyword">this</span>.viewAccessCache.put(cacheKey, view);</span><br><span class="line">                        <span class="keyword">this</span>.viewCreationCache.put(cacheKey, view);</span><br><span class="line">                        <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">                            logger.trace(<span class="string">"Cached view ["</span> + cacheKey + <span class="string">"]"</span>);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> (view != UNRESOLVED_VIEW ? view : <span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Create the actual View object.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;The default implementation delegates to &#123;<span class="doctag">@link</span> #loadView&#125;.</span></span><br><span class="line"><span class="comment"> * This can be overridden to resolve certain view names in a special fashion,</span></span><br><span class="line"><span class="comment"> * before delegating to the actual &#123;<span class="doctag">@code</span> loadView&#125; implementation</span></span><br><span class="line"><span class="comment"> * provided by the subclass.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> viewName the name of the view to retrieve</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> locale the Locale to retrieve the view for</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the View instance, or &#123;<span class="doctag">@code</span> null&#125; if not found</span></span><br><span class="line"><span class="comment"> * (optional, to allow for ViewResolver chaining)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception if the view couldn't be resolved</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #loadView</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> View <span class="title">createView</span><span class="params">(String viewName, Locale locale)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> loadView(viewName, locale);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Subclasses must implement this method, building a View object</span></span><br><span class="line"><span class="comment"> * for the specified view. The returned View objects will be</span></span><br><span class="line"><span class="comment"> * cached by this ViewResolver base class.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Subclasses are not forced to support internationalization:</span></span><br><span class="line"><span class="comment"> * A subclass that does not may simply ignore the locale parameter.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> viewName the name of the view to retrieve</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> locale the Locale to retrieve the view for</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the View instance, or &#123;<span class="doctag">@code</span> null&#125; if not found</span></span><br><span class="line"><span class="comment"> * (optional, to allow for ViewResolver chaining)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception if the view couldn't be resolved</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #resolveViewName</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> View <span class="title">loadView</span><span class="params">(String viewName, Locale locale)</span> <span class="keyword">throws</span> Exception</span>;</span><br></pre></td></tr></table></figure>

<p>这个类留给子类的接口是loadView方法。</p>
<h3 id="5-5-XmlViewResolver-分析"><a href="#5-5-XmlViewResolver-分析" class="headerlink" title="5.5 XmlViewResolver 分析"></a>5.5 XmlViewResolver 分析</h3><p>XmlViewResolver 是一个比较奇葩的类，实现的功能比较奇葩，他会从指定的xml配置文件中根据beanName来获取View。是不是和 BeanNameViewResolver 很像？不过他俩的区别是：XmlViewResolver 会再生成一个应用上下文单独加载一套xml配置文件，还需要维护自己的应用上下文的生命周期。BeanNameViewResolver 则是简单地直接从现有的应用上下文获取View。</p>
<p>直接来看类的源码吧</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">XmlViewResolver</span> <span class="keyword">extends</span> <span class="title">AbstractCachingViewResolver</span></span></span><br><span class="line"><span class="class">        <span class="keyword">implements</span> <span class="title">Ordered</span>, <span class="title">InitializingBean</span>, <span class="title">DisposableBean</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/** Default if no other location is supplied */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> String DEFAULT_LOCATION = <span class="string">"/WEB-INF/views.xml"</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> order = Integer.MAX_VALUE;  <span class="comment">// default: same as non-Ordered</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Resource location;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> ConfigurableApplicationContext cachedFactory;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setOrder</span><span class="params">(<span class="keyword">int</span> order)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.order = order;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getOrder</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.order;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Set the location of the XML file that defines the view beans.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;The default is "/WEB-INF/views.xml".</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> location the location of the XML file.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setLocation</span><span class="params">(Resource location)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.location = location;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Pre-initialize the factory from the XML file.</span></span><br><span class="line"><span class="comment">     * Only effective if caching is enabled.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (isCache()) &#123;</span><br><span class="line">            initFactory();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * This implementation returns just the view name,</span></span><br><span class="line"><span class="comment">     * as XmlViewResolver doesn't support localized resolution.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Object <span class="title">getCacheKey</span><span class="params">(String viewName, Locale locale)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> viewName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> View <span class="title">loadView</span><span class="params">(String viewName, Locale locale)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">        BeanFactory factory = initFactory();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> factory.getBean(viewName, View<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (NoSuchBeanDefinitionException ex) &#123;</span><br><span class="line">            <span class="comment">// Allow for ViewResolver chaining...</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Initialize the view bean factory from the XML file.</span></span><br><span class="line"><span class="comment">     * Synchronized because of access by parallel threads.</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> BeansException in case of initialization errors</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">synchronized</span> BeanFactory <span class="title">initFactory</span><span class="params">()</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.cachedFactory != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>.cachedFactory;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        Resource actualLocation = <span class="keyword">this</span>.location;</span><br><span class="line">        <span class="keyword">if</span> (actualLocation == <span class="keyword">null</span>) &#123;</span><br><span class="line">            actualLocation = getApplicationContext().getResource(DEFAULT_LOCATION);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Create child ApplicationContext for views.</span></span><br><span class="line">        GenericWebApplicationContext factory = <span class="keyword">new</span> GenericWebApplicationContext();</span><br><span class="line">        factory.setParent(getApplicationContext());</span><br><span class="line">        factory.setServletContext(getServletContext());</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Load XML resource with context-aware entity resolver.</span></span><br><span class="line">        XmlBeanDefinitionReader reader = <span class="keyword">new</span> XmlBeanDefinitionReader(factory);</span><br><span class="line">        reader.setEnvironment(getApplicationContext().getEnvironment());</span><br><span class="line">        reader.setEntityResolver(<span class="keyword">new</span> ResourceEntityResolver(getApplicationContext()));</span><br><span class="line">        reader.loadBeanDefinitions(actualLocation);</span><br><span class="line"></span><br><span class="line">        factory.refresh();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (isCache()) &#123;</span><br><span class="line">            <span class="keyword">this</span>.cachedFactory = factory;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> factory;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Close the view bean factory on context shutdown.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">destroy</span><span class="params">()</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.cachedFactory != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">this</span>.cachedFactory.close();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-6-ResourceBundleViewResolver-分析"><a href="#5-6-ResourceBundleViewResolver-分析" class="headerlink" title="5.6 ResourceBundleViewResolver 分析"></a>5.6 ResourceBundleViewResolver 分析</h3><p>ResourceBundleViewResolver 类允许用户指定一个属性文件，然后在属性文件中配置viewName和对应View实现类，以及viewName和对应的模板页面。</p>
<p>例如在xml这样配置</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.web.servlet.view.ResourceBundleViewResolver"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 设定属性文件名为views 默认也为views --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"basename"</span> <span class="attr">value</span>=<span class="string">"views"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>接下来在resources文件夹下创建views.properties文件，配置上以下内容</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">a.class</span>=<span class="string">org.springframework.web.servlet.view.JstlView</span></span><br><span class="line"><span class="meta">a.url</span>=<span class="string">/WEB-INF/jsp/a.jsp</span></span><br><span class="line"><span class="meta">b.class</span>=<span class="string">org.springframework.web.servlet.view.JstlView</span></span><br><span class="line"><span class="meta">b.url</span>=<span class="string">/WEB-INF/jsp/b.jsp</span></span><br></pre></td></tr></table></figure>

<p>即可实现viewName为a时使用JstlView，模板为/WEB-INF/jsp/a.jsp。</p>
<h3 id="5-7-UrlBasedViewResolver-分析"><a href="#5-7-UrlBasedViewResolver-分析" class="headerlink" title="5.7 UrlBasedViewResolver 分析"></a>5.7 UrlBasedViewResolver 分析</h3><p>AbstractCachingViewResolver 的上两个实现类实际上用的频率很少，用的比较多的就是 UrlBasedViewResolver 的子类，在这里，我们先看看 UrlBasedViewResolver 都做了些什么事。</p>
<p>首先，需要设置一个viewClass，而这个class必须继承 requiredViewClass 方法获取到的类，在这个类中，requiredViewClass 方法获取到的类是 AbstractUrlBasedView</p>
<p>代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Set the view class that should be used to create views.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> viewClass class that is assignable to the required view class</span></span><br><span class="line"><span class="comment"> * (by default, AbstractUrlBasedView)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> AbstractUrlBasedView</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setViewClass</span><span class="params">(Class&lt;?&gt; viewClass)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (viewClass == <span class="keyword">null</span> || !requiredViewClass().isAssignableFrom(viewClass)) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(</span><br><span class="line">                <span class="string">"Given view class ["</span> + (viewClass != <span class="keyword">null</span> ? viewClass.getName() : <span class="keyword">null</span>) +</span><br><span class="line">                <span class="string">"] is not of type ["</span> + requiredViewClass().getName() + <span class="string">"]"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">this</span>.viewClass = viewClass;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Return the view class to be used to create views.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">protected</span> Class&lt;?&gt; getViewClass() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.viewClass;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Return the required type of view for this resolver.</span></span><br><span class="line"><span class="comment"> * This implementation returns AbstractUrlBasedView.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> AbstractUrlBasedView</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">protected</span> Class&lt;?&gt; requiredViewClass() &#123;</span><br><span class="line">    <span class="keyword">return</span> AbstractUrlBasedView<span class="class">.<span class="keyword">class</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initApplicationContext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>.initApplicationContext();</span><br><span class="line">    <span class="keyword">if</span> (getViewClass() == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Property 'viewClass' is required"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其次，它还重写了 AbstractCachingViewResolver 类的createView方法，在方法中先判断是否有匹配的viewName，在判断是不是重定向或forward，最后再调用父类方法。</p>
<p>代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Overridden to implement check for "redirect:" prefix.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Not possible in &#123;<span class="doctag">@code</span> loadView&#125;, since overridden</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@code</span> loadView&#125; versions in subclasses might rely on the</span></span><br><span class="line"><span class="comment"> * superclass always creating instances of the required view class.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #loadView</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #requiredViewClass</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> View <span class="title">createView</span><span class="params">(String viewName, Locale locale)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// If this resolver is not supposed to handle the given view,</span></span><br><span class="line">    <span class="comment">// return null to pass on to the next resolver in the chain.</span></span><br><span class="line">    <span class="keyword">if</span> (!canHandle(viewName, locale)) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Check for special "redirect:" prefix.</span></span><br><span class="line">    <span class="keyword">if</span> (viewName.startsWith(REDIRECT_URL_PREFIX)) &#123;</span><br><span class="line">        String redirectUrl = viewName.substring(REDIRECT_URL_PREFIX.length());</span><br><span class="line">        RedirectView view = <span class="keyword">new</span> RedirectView(redirectUrl, isRedirectContextRelative(), isRedirectHttp10Compatible());</span><br><span class="line">        view.setHosts(getRedirectHosts());</span><br><span class="line">        <span class="keyword">return</span> applyLifecycleMethods(viewName, view);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Check for special "forward:" prefix.</span></span><br><span class="line">    <span class="keyword">if</span> (viewName.startsWith(FORWARD_URL_PREFIX)) &#123;</span><br><span class="line">        String forwardUrl = viewName.substring(FORWARD_URL_PREFIX.length());</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> InternalResourceView(forwardUrl);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Else fall back to superclass implementation: calling loadView.</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">super</span>.createView(viewName, locale);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Indicates whether or not this &#123;<span class="doctag">@link</span> org.springframework.web.servlet.ViewResolver&#125; can</span></span><br><span class="line"><span class="comment"> * handle the supplied view name. If not, &#123;<span class="doctag">@link</span> #createView(String, java.util.Locale)&#125; will</span></span><br><span class="line"><span class="comment"> * return &#123;<span class="doctag">@code</span> null&#125;. The default implementation checks against the configured</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> #setViewNames view names&#125;.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> viewName the name of the view to retrieve</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> locale the Locale to retrieve the view for</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> whether this resolver applies to the specified view</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.util.PatternMatchUtils#simpleMatch(String, String)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">canHandle</span><span class="params">(String viewName, Locale locale)</span> </span>&#123;</span><br><span class="line">    String[] viewNames = getViewNames();</span><br><span class="line">    <span class="keyword">return</span> (viewNames == <span class="keyword">null</span> || PatternMatchUtils.simpleMatch(viewNames, viewName));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>重定向和forward这里暂时不考虑，我们先看看正常的怎么调用。</p>
<p>UrlBasedViewResolver 允许设置prefix和suffix，使得开发者返回viewName时，只用返回特征值即可。例如文件在<code>/WEB-INF/static/</code>下,文件结尾是<code>.html</code>，那么设置prefix为<code>/WEB-INF/static/</code>，suffix为<code>.html</code>，如果想获取<code>/WEB-INF/static/a.html</code>，开发者只用设置viewName为a即可。</p>
<p>UrlBasedViewResolver 重写了loadView方法，实现了根据文件名加载View的基本逻辑。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Delegates to &#123;<span class="doctag">@code</span> buildView&#125; for creating a new instance of the</span></span><br><span class="line"><span class="comment"> * specified view class, and applies the following Spring lifecycle methods</span></span><br><span class="line"><span class="comment"> * (as supported by the generic Spring bean factory):</span></span><br><span class="line"><span class="comment"> * &lt;ul&gt;</span></span><br><span class="line"><span class="comment"> * &lt;li&gt;ApplicationContextAware's &#123;<span class="doctag">@code</span> setApplicationContext&#125;</span></span><br><span class="line"><span class="comment"> * &lt;li&gt;InitializingBean's &#123;<span class="doctag">@code</span> afterPropertiesSet&#125;</span></span><br><span class="line"><span class="comment"> * &lt;/ul&gt;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> viewName the name of the view to retrieve</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the View instance</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception if the view couldn't be resolved</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #buildView(String)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.context.ApplicationContextAware#setApplicationContext</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.beans.factory.InitializingBean#afterPropertiesSet</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> View <span class="title">loadView</span><span class="params">(String viewName, Locale locale)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    AbstractUrlBasedView view = buildView(viewName);</span><br><span class="line">    View result = applyLifecycleMethods(viewName, view);</span><br><span class="line">    <span class="keyword">return</span> (view.checkResource(locale) ? result : <span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> View <span class="title">applyLifecycleMethods</span><span class="params">(String viewName, AbstractView view)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> (View) getApplicationContext().getAutowireCapableBeanFactory().initializeBean(view, viewName);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Creates a new View instance of the specified view class and configures it.</span></span><br><span class="line"><span class="comment"> * Does &lt;i&gt;not&lt;/i&gt; perform any lookup for pre-defined View instances.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Spring lifecycle methods as defined by the bean container do not have to</span></span><br><span class="line"><span class="comment"> * be called here; those will be applied by the &#123;<span class="doctag">@code</span> loadView&#125; method</span></span><br><span class="line"><span class="comment"> * after this method returns.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Subclasses will typically call &#123;<span class="doctag">@code</span> super.buildView(viewName)&#125;</span></span><br><span class="line"><span class="comment"> * first, before setting further properties themselves. &#123;<span class="doctag">@code</span> loadView&#125;</span></span><br><span class="line"><span class="comment"> * will then apply Spring lifecycle methods at the end of this process.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> viewName the name of the view to build</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the View instance</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception if the view couldn't be resolved</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #loadView(String, java.util.Locale)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> AbstractUrlBasedView <span class="title">buildView</span><span class="params">(String viewName)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    AbstractUrlBasedView view = (AbstractUrlBasedView) BeanUtils.instantiateClass(getViewClass());</span><br><span class="line">    view.setUrl(getPrefix() + viewName + getSuffix());</span><br><span class="line">    String contentType = getContentType();</span><br><span class="line">    <span class="keyword">if</span> (contentType != <span class="keyword">null</span>) &#123;</span><br><span class="line">        view.setContentType(contentType);</span><br><span class="line">    &#125;</span><br><span class="line">    view.setRequestContextAttribute(getRequestContextAttribute());</span><br><span class="line">    view.setAttributesMap(getAttributesMap());</span><br><span class="line">    Boolean exposePathVariables = getExposePathVariables();</span><br><span class="line">    <span class="keyword">if</span> (exposePathVariables != <span class="keyword">null</span>) &#123;</span><br><span class="line">        view.setExposePathVariables(exposePathVariables);</span><br><span class="line">    &#125;</span><br><span class="line">    Boolean exposeContextBeansAsAttributes = getExposeContextBeansAsAttributes();</span><br><span class="line">    <span class="keyword">if</span> (exposeContextBeansAsAttributes != <span class="keyword">null</span>) &#123;</span><br><span class="line">        view.setExposeContextBeansAsAttributes(exposeContextBeansAsAttributes);</span><br><span class="line">    &#125;</span><br><span class="line">    String[] exposedContextBeanNames = getExposedContextBeanNames();</span><br><span class="line">    <span class="keyword">if</span> (exposedContextBeanNames != <span class="keyword">null</span>) &#123;</span><br><span class="line">        view.setExposedContextBeanNames(exposedContextBeanNames);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> view;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-8-InternalResourceViewResolver-分析"><a href="#5-8-InternalResourceViewResolver-分析" class="headerlink" title="5.8 InternalResourceViewResolver 分析"></a>5.8 InternalResourceViewResolver 分析</h3><p>InternalResourceViewResolver ？内部资源视图解析器？干什么的呢？实际上，这是一个利用jstl标准标签库实现模板渲染的视图解析器。只要类路径中存在<code>javax.servlet.jsp.jstl.core.Config</code>类，说明jstl标准标签库可以使用。来看看它是如何设置viewClass的吧。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Sets the default &#123;<span class="doctag">@link</span> #setViewClass view class&#125; to &#123;<span class="doctag">@link</span> #requiredViewClass&#125;:</span></span><br><span class="line"><span class="comment"> * by default &#123;<span class="doctag">@link</span> InternalResourceView&#125;, or &#123;<span class="doctag">@link</span> JstlView&#125; if the JSTL API</span></span><br><span class="line"><span class="comment"> * is present.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">InternalResourceViewResolver</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    Class&lt;?&gt; viewClass = requiredViewClass();</span><br><span class="line">    <span class="keyword">if</span> (InternalResourceView<span class="class">.<span class="keyword">class</span> </span>== viewClass &amp;&amp; jstlPresent) &#123;</span><br><span class="line">        viewClass = JstlView<span class="class">.<span class="keyword">class</span></span>;</span><br><span class="line">    &#125;</span><br><span class="line">    setViewClass(viewClass);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * A convenience constructor that allows for specifying &#123;<span class="doctag">@link</span> #setPrefix prefix&#125;</span></span><br><span class="line"><span class="comment"> * and &#123;<span class="doctag">@link</span> #setSuffix suffix&#125; as constructor arguments.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> prefix the prefix that gets prepended to view names when building a URL</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> suffix the suffix that gets appended to view names when building a URL</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@since</span> 4.3</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">InternalResourceViewResolver</span><span class="params">(String prefix, String suffix)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>();</span><br><span class="line">    setPrefix(prefix);</span><br><span class="line">    setSuffix(suffix);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * This resolver requires &#123;<span class="doctag">@link</span> InternalResourceView&#125;.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="keyword">protected</span> Class&lt;?&gt; requiredViewClass() &#123;</span><br><span class="line">    <span class="keyword">return</span> InternalResourceView<span class="class">.<span class="keyword">class</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-9-AbstractTemplateViewResolver-分析"><a href="#5-9-AbstractTemplateViewResolver-分析" class="headerlink" title="5.9 AbstractTemplateViewResolver 分析"></a>5.9 AbstractTemplateViewResolver 分析</h3><p>使用过jsp当模板引擎后，很多人觉得可能有点复杂，那我要是想使用别的模板引擎呢？ 对喽，这里提供了一个类供模板引擎使用。这个类的作用是什么？因为模板引擎实质上就是修改字符串，跟httpRequest没有关系，所以如果要使用模板引擎，就要判断request中的属性、session中的属性要不要给模板引擎提供。AbstractTemplateViewResolver 就实现了这样的功能，它对应的View是 AbstractTemplateView。</p>
<h3 id="5-10-FreeMarkerViewResolver-分析"><a href="#5-10-FreeMarkerViewResolver-分析" class="headerlink" title="5.10 FreeMarkerViewResolver 分析"></a>5.10 FreeMarkerViewResolver 分析</h3><p>FreeMarkerViewResolver 继承了 AbstractTemplateViewResolver，实际上，FreeMarkerViewResolver提供了View的实现类 FreeMarkerView 供  UrlBasedViewResolver 创建View。</p>
<h3 id="5-11-小结"><a href="#5-11-小结" class="headerlink" title="5.11 小结"></a>5.11 小结</h3><p>看完这么多 ViewResolver 的实现，我们发现实际上通过viewName获取View实现类分为这几种。</p>
<ul>
<li>第一种是直接从web应用上下文找name为viewName的bean。</li>
<li>第二种是从指定配置文件加载应用上下文，再在上下文中查找name为viewName的bean。</li>
<li>第三种是通过判断viewName对应的文件是否存在来决定是否适用该View。</li>
</ul>
<h2 id="6-View"><a href="#6-View" class="headerlink" title="6 View"></a>6 View</h2><img src="http://www.plantuml.com/plantuml/svg/bL7DJiCm3BxdANpSnDOdc420G82qopQuPwtNLKsJu7Wj2FRkfCsOklv8a4kYxoVsPmihuroc28RIo5dATBeZMM1bA8ygt4OEgLJ8y2K4-9DfHjh96E4jmygZS3fNiERQ3IdolV4gpPjFYvDfIr6QB052dI1Dbj8kWcC6DzTGc0JL39wOxJfKNE7x0HrxVNDtE6UDTkZ9y9W2xybK3Xu-OhIS6TsKFOgZ47zC69KXK6EKMySaOuRRqwDEEyoyahgJ3fDnnGOBgoJZMH4hwHmyrwFKKlamva1nbtvnh3hG2fECiDLCiuF5ztpUxxCDN4fw3GyHbvPUWd7BQAfnIo_Mq1z1UXxAVnSRxGYna9GZ_UuupFJHuyi6xtNQJXtATyI-YHy0">

<p>第5章讲完了 ViewResolver，我们发现一个干事的 ViewResolver 后边对应的时一个或多个View实现类。因此，我们来了解一下View及其实现类吧。</p>
<h3 id="6-1-AbstractView-分析"><a href="#6-1-AbstractView-分析" class="headerlink" title="6.1 AbstractView 分析"></a>6.1 AbstractView 分析</h3><h4 id="6-1-1-AbstractView-初始化分析"><a href="#6-1-1-AbstractView-初始化分析" class="headerlink" title="6.1.1 AbstractView 初始化分析"></a>6.1.1 AbstractView 初始化分析</h4><p>首先，AbstractView 有两个常量，分别是：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** Default content type. Overridable as bean property. */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String DEFAULT_CONTENT_TYPE = <span class="string">"text/html;charset=ISO-8859-1"</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** Initial size for the temporary output byte array (if any) */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> OUTPUT_BYTE_ARRAY_INITIAL_SIZE = <span class="number">4096</span>;</span><br></pre></td></tr></table></figure>

<p>第一个常量<code>DEFAULT_CONTENT_TYPE</code>用于填充默认的ContentType，第二个常量<code>OUTPUT_BYTE_ARRAY_INITIAL_SIZE</code>是生成ByteArrayOutputStream的默认初始值。</p>
<p>其次，AbstractView 实现了BeanNameAware接口，可以得到自身的name。</p>
<h4 id="6-1-2-AbstractView-处理请求分析"><a href="#6-1-2-AbstractView-处理请求分析" class="headerlink" title="6.1.2 AbstractView 处理请求分析"></a>6.1.2 AbstractView 处理请求分析</h4><p>AbstractView 重写了render方法，并将代码分为三步完成请求。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Prepares the view given the specified model, merging it with static</span></span><br><span class="line"><span class="comment"> * attributes and a RequestContext attribute, if necessary.</span></span><br><span class="line"><span class="comment"> * Delegates to renderMergedOutputModel for the actual rendering.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #renderMergedOutputModel</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">render</span><span class="params">(Map&lt;String, ?&gt; model, HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">        logger.trace(<span class="string">"Rendering view with name '"</span> + <span class="keyword">this</span>.beanName + <span class="string">"' with model "</span> + model +</span><br><span class="line">            <span class="string">" and static attributes "</span> + <span class="keyword">this</span>.staticAttributes);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Map&lt;String, Object&gt; mergedModel = createMergedOutputModel(model, request, response);</span><br><span class="line">    prepareResponse(request, response);</span><br><span class="line">    renderMergedOutputModel(mergedModel, getRequestToExpose(request), response);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Creates a combined output Map (never &#123;<span class="doctag">@code</span> null&#125;) that includes dynamic values and static attributes.</span></span><br><span class="line"><span class="comment"> * Dynamic values take precedence over static attributes.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Map&lt;String, Object&gt; <span class="title">createMergedOutputModel</span><span class="params">(Map&lt;String, ?&gt; model, HttpServletRequest request,</span></span></span><br><span class="line"><span class="function"><span class="params">        HttpServletResponse response)</span> </span>&#123;</span><br><span class="line">    <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">    Map&lt;String, Object&gt; pathVars = (<span class="keyword">this</span>.exposePathVariables ?</span><br><span class="line">            (Map&lt;String, Object&gt;) request.getAttribute(View.PATH_VARIABLES) : <span class="keyword">null</span>);</span><br><span class="line">    <span class="comment">// Consolidate static and dynamic model attributes.</span></span><br><span class="line">    <span class="keyword">int</span> size = <span class="keyword">this</span>.staticAttributes.size();</span><br><span class="line">    size += (model != <span class="keyword">null</span> ? model.size() : <span class="number">0</span>);</span><br><span class="line">    size += (pathVars != <span class="keyword">null</span> ? pathVars.size() : <span class="number">0</span>);</span><br><span class="line">    Map&lt;String, Object&gt; mergedModel = <span class="keyword">new</span> LinkedHashMap&lt;String, Object&gt;(size);</span><br><span class="line">    mergedModel.putAll(<span class="keyword">this</span>.staticAttributes);</span><br><span class="line">    <span class="keyword">if</span> (pathVars != <span class="keyword">null</span>) &#123;</span><br><span class="line">        mergedModel.putAll(pathVars);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (model != <span class="keyword">null</span>) &#123;</span><br><span class="line">        mergedModel.putAll(model);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Expose RequestContext?</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.requestContextAttribute != <span class="keyword">null</span>) &#123;</span><br><span class="line">        mergedModel.put(<span class="keyword">this</span>.requestContextAttribute, createRequestContext(request, response, mergedModel));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> mergedModel;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Prepare the given response for rendering.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;The default implementation applies a workaround for an IE bug</span></span><br><span class="line"><span class="comment"> * when sending download content via HTTPS.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> response current HTTP response</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">prepareResponse</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (generatesDownloadContent()) &#123;</span><br><span class="line">        response.setHeader(<span class="string">"Pragma"</span>, <span class="string">"private"</span>);</span><br><span class="line">        response.setHeader(<span class="string">"Cache-Control"</span>, <span class="string">"private, must-revalidate"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Subclasses must implement this method to actually render the view.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;The first step will be preparing the request: In the JSP case,</span></span><br><span class="line"><span class="comment"> * this would mean setting model objects as request attributes.</span></span><br><span class="line"><span class="comment"> * The second step will be the actual rendering of the view,</span></span><br><span class="line"><span class="comment"> * for example including the JSP via a RequestDispatcher.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> model combined output Map (never &#123;<span class="doctag">@code</span> null&#125;),</span></span><br><span class="line"><span class="comment"> * with dynamic values taking precedence over static attributes</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> response current HTTP response</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception if rendering failed</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">renderMergedOutputModel</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        Map&lt;String, Object&gt; model, HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception</span>;</span><br></pre></td></tr></table></figure>

<p>首先第一步是生成一个最终的model，在 AbstractView 中，会将其Map类型的属性 staticAttributes 合并到传入的model中。如果允许暴露 RequestContext，则将 RequestContext传入。</p>
<p>其次是准备响应，这里一般不会运行什么结果。</p>
<p>最后是将合并后的model交给子类渲染。</p>
<h4 id="6-1-3-AbstractView-其他"><a href="#6-1-3-AbstractView-其他" class="headerlink" title="6.1.3 AbstractView 其他"></a>6.1.3 AbstractView 其他</h4><p>除以上处理请求方法外，AbstractView 还提供了一些设置请求头、把ByteArrayOutputStream写入response等等供子类调用的方法，方便子类使用。</p>
<h3 id="6-2-AbstractUrlBasedView-分析"><a href="#6-2-AbstractUrlBasedView-分析" class="headerlink" title="6.2 AbstractUrlBasedView 分析"></a>6.2 AbstractUrlBasedView 分析</h3><p>AbstractUrlBasedView 是最简单的View之一，它提供了一个url属性。还有个checkResource方法，这个方法就是在 UrlBasedViewResolver 类中loadView方法内最终检测文件是否存在的方法。</p>
<h3 id="6-3-InternalResourceView-和-JstlView"><a href="#6-3-InternalResourceView-和-JstlView" class="headerlink" title="6.3 InternalResourceView 和 JstlView"></a>6.3 InternalResourceView 和 JstlView</h3><p>我们在5.8节讲到 InternalResourceViewResolver 使用的View就是InternalResourceView和JstlView。InternalResourceView 能够渲染jsp页面，代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Render the internal resource given the specified model.</span></span><br><span class="line"><span class="comment"> * This includes setting the model as request attributes.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">renderMergedOutputModel</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        Map&lt;String, Object&gt; model, HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// Expose the model object as request attributes.</span></span><br><span class="line">    exposeModelAsRequestAttributes(model, request);</span><br><span class="line">    <span class="comment">// Expose helpers as request attributes, if any.</span></span><br><span class="line">    exposeHelpers(request);</span><br><span class="line">    <span class="comment">// Determine the path for the request dispatcher.</span></span><br><span class="line">    String dispatcherPath = prepareForRendering(request, response);</span><br><span class="line">    <span class="comment">// Obtain a RequestDispatcher for the target resource (typically a JSP).</span></span><br><span class="line">    RequestDispatcher rd = getRequestDispatcher(request, dispatcherPath);</span><br><span class="line">    <span class="keyword">if</span> (rd == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ServletException(<span class="string">"Could not get RequestDispatcher for ["</span> + getUrl() +</span><br><span class="line">                <span class="string">"]: Check that the corresponding file exists within your web application archive!"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// If already included or response already committed, perform include, else forward.</span></span><br><span class="line">    <span class="keyword">if</span> (useInclude(request, response)) &#123;</span><br><span class="line">        response.setContentType(getContentType());</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Including resource ["</span> + getUrl() + <span class="string">"] in InternalResourceView '"</span> + getBeanName() + <span class="string">"'"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        rd.include(request, response);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// Note: The forwarded resource is supposed to determine the content type itself.</span></span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Forwarding to resource ["</span> + getUrl() + <span class="string">"] in InternalResourceView '"</span> + getBeanName() + <span class="string">"'"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        rd.forward(request, response);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如上代码，首先将model中的K-V值放到了request的属性中，接下来调用RequestDispatcher的include或forward方法执行渲染，这里就不做细究了。</p>
<p>如果项目中引入了JSTL标准标签库，则会使用 JstlView，引入一些JSTL需要使用的数据。</p>
<h3 id="6-4-RedirectView-分析"><a href="#6-4-RedirectView-分析" class="headerlink" title="6.4 RedirectView 分析"></a>6.4 RedirectView 分析</h3><p>由于在 UrlBasedViewResolver 中重写了 createView方法，判断如果viewName是以redirect开头的，就会重定向到别的页面，使用的就是 RedirectView。</p>
<p>在redirect时，会将相关数据保存在 FlashMap中，这个咱们在<code>DispatcherServlet</code>讲过,用于保存重定向前相关数据。保存好相关数据后，再向response中写入Header信息，K为Location，V为跳转的URL。</p>
<p>相关方法如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Convert model to request parameters and redirect to the given URL.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #appendQueryProperties</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #sendRedirect</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">renderMergedOutputModel</span><span class="params">(Map&lt;String, Object&gt; model, HttpServletRequest request,</span></span></span><br><span class="line"><span class="function"><span class="params">        HttpServletResponse response)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    String targetUrl = createTargetUrl(model, request);</span><br><span class="line">    targetUrl = updateTargetUrl(targetUrl, model, request, response);</span><br><span class="line">    FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);</span><br><span class="line">    <span class="keyword">if</span> (!CollectionUtils.isEmpty(flashMap)) &#123;</span><br><span class="line">        UriComponents uriComponents = UriComponentsBuilder.fromUriString(targetUrl).build();</span><br><span class="line">        flashMap.setTargetRequestPath(uriComponents.getPath());</span><br><span class="line">        flashMap.addTargetRequestParams(uriComponents.getQueryParams());</span><br><span class="line">        FlashMapManager flashMapManager = RequestContextUtils.getFlashMapManager(request);</span><br><span class="line">        <span class="keyword">if</span> (flashMapManager == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">"FlashMapManager not found despite output FlashMap having been set"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        flashMapManager.saveOutputFlashMap(flashMap, request, response);</span><br><span class="line">    &#125;</span><br><span class="line">    sendRedirect(request, response, targetUrl, <span class="keyword">this</span>.http10Compatible);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Send a redirect back to the HTTP client</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request (allows for reacting to request method)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> response current HTTP response (for sending response headers)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> targetUrl the target URL to redirect to</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> http10Compatible whether to stay compatible with HTTP 1.0 clients</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> IOException if thrown by response methods</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">sendRedirect</span><span class="params">(HttpServletRequest request, HttpServletResponse response,</span></span></span><br><span class="line"><span class="function"><span class="params">        String targetUrl, <span class="keyword">boolean</span> http10Compatible)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    String encodedURL = (isRemoteHost(targetUrl) ? targetUrl : response.encodeRedirectURL(targetUrl));</span><br><span class="line">    <span class="keyword">if</span> (http10Compatible) &#123;</span><br><span class="line">        HttpStatus attributeStatusCode = (HttpStatus) request.getAttribute(View.RESPONSE_STATUS_ATTRIBUTE);</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.statusCode != <span class="keyword">null</span>) &#123;</span><br><span class="line">            response.setStatus(<span class="keyword">this</span>.statusCode.value());</span><br><span class="line">            response.setHeader(<span class="string">"Location"</span>, encodedURL);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (attributeStatusCode != <span class="keyword">null</span>) &#123;</span><br><span class="line">            response.setStatus(attributeStatusCode.value());</span><br><span class="line">            response.setHeader(<span class="string">"Location"</span>, encodedURL);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// Send status code 302 by default.</span></span><br><span class="line">            response.sendRedirect(encodedURL);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        HttpStatus statusCode = getHttp11StatusCode(request, response, targetUrl);</span><br><span class="line">        response.setStatus(statusCode.value());</span><br><span class="line">        response.setHeader(<span class="string">"Location"</span>, encodedURL);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="6-5-AbstractTemplateView-分析"><a href="#6-5-AbstractTemplateView-分析" class="headerlink" title="6.5 AbstractTemplateView 分析"></a>6.5 AbstractTemplateView 分析</h3><p>AbstractTemplateView 是在 AbstractTemplateViewResolver 中使用的，抽象模板视图的作用是决定要不要将HTTPrequest中的相关信息写入model。还记得6.3节InternalResourceView和JstlView吗？在那些View中，是需要将model写入到request的属性中。而模板引擎在非web程序中也能使用，和request一点关系都没有，所以，为了能让模板引擎能够拿到request中的数据，设置了该抽象类，用于决定要不要将request中的信息写入到model中。</p>
<p>以下是相关属性：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Variable name of the RequestContext instance in the template model,</span></span><br><span class="line"><span class="comment"> * available to Spring's macros: e.g. for creating BindStatus objects.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE = <span class="string">"springMacroRequestContext"</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 是否将request属性中的信息写入到model</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">boolean</span> exposeRequestAttributes = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 是否允许request的信息覆盖model的</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">boolean</span> allowRequestOverride = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 是否将session中的信息写入到model</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">boolean</span> exposeSessionAttributes = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 是否允许session的信息覆盖model的</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">boolean</span> allowSessionOverride = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 是否暴露spring上下文</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">boolean</span> exposeSpringMacroHelpers = <span class="keyword">true</span>;</span><br></pre></td></tr></table></figure>

<p>了解了这些信息，来看看相关代码吧</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">renderMergedOutputModel</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        Map&lt;String, Object&gt; model, HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.exposeRequestAttributes) &#123;</span><br><span class="line">        <span class="keyword">for</span> (Enumeration&lt;String&gt; en = request.getAttributeNames(); en.hasMoreElements();) &#123;</span><br><span class="line">            String attribute = en.nextElement();</span><br><span class="line">            <span class="keyword">if</span> (model.containsKey(attribute) &amp;&amp; !<span class="keyword">this</span>.allowRequestOverride) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> ServletException(<span class="string">"Cannot expose request attribute '"</span> + attribute +</span><br><span class="line">                    <span class="string">"' because of an existing model object of the same name"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            Object attributeValue = request.getAttribute(attribute);</span><br><span class="line">            <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">                logger.debug(<span class="string">"Exposing request attribute '"</span> + attribute +</span><br><span class="line">                        <span class="string">"' with value ["</span> + attributeValue + <span class="string">"] to model"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            model.put(attribute, attributeValue);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.exposeSessionAttributes) &#123;</span><br><span class="line">        HttpSession session = request.getSession(<span class="keyword">false</span>);</span><br><span class="line">        <span class="keyword">if</span> (session != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">for</span> (Enumeration&lt;String&gt; en = session.getAttributeNames(); en.hasMoreElements();) &#123;</span><br><span class="line">                String attribute = en.nextElement();</span><br><span class="line">                <span class="keyword">if</span> (model.containsKey(attribute) &amp;&amp; !<span class="keyword">this</span>.allowSessionOverride) &#123;</span><br><span class="line">                    <span class="keyword">throw</span> <span class="keyword">new</span> ServletException(<span class="string">"Cannot expose session attribute '"</span> + attribute +</span><br><span class="line">                        <span class="string">"' because of an existing model object of the same name"</span>);</span><br><span class="line">                &#125;</span><br><span class="line">                Object attributeValue = session.getAttribute(attribute);</span><br><span class="line">                <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">                    logger.debug(<span class="string">"Exposing session attribute '"</span> + attribute +</span><br><span class="line">                            <span class="string">"' with value ["</span> + attributeValue + <span class="string">"] to model"</span>);</span><br><span class="line">                &#125;</span><br><span class="line">                model.put(attribute, attributeValue);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.exposeSpringMacroHelpers) &#123;</span><br><span class="line">        <span class="keyword">if</span> (model.containsKey(SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE)) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ServletException(</span><br><span class="line">                    <span class="string">"Cannot expose bind macro helper '"</span> + SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE +</span><br><span class="line">                    <span class="string">"' because of an existing model object of the same name"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// Expose RequestContext instance for Spring macros.</span></span><br><span class="line">        model.put(SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE,</span><br><span class="line">                <span class="keyword">new</span> RequestContext(request, response, getServletContext(), model));</span><br><span class="line">    &#125;</span><br><span class="line">    applyContentType(response);</span><br><span class="line">    renderMergedTemplateModel(model, request, response);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Apply this view's content type as specified in the "contentType"</span></span><br><span class="line"><span class="comment"> * bean property to the given response.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Only applies the view's contentType if no content type has been</span></span><br><span class="line"><span class="comment"> * set on the response before. This allows handlers to override the</span></span><br><span class="line"><span class="comment"> * default content type beforehand.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> response current HTTP response</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #setContentType</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">applyContentType</span><span class="params">(HttpServletResponse response)</span>   </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (response.getContentType() == <span class="keyword">null</span>) &#123;</span><br><span class="line">        response.setContentType(getContentType());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Subclasses must implement this method to actually render the view.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> model combined output Map, with request attributes and</span></span><br><span class="line"><span class="comment"> * session attributes merged into it if required</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> response current HTTP response</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception if rendering failed</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">renderMergedTemplateModel</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        Map&lt;String, Object&gt; model, HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception</span>;</span><br></pre></td></tr></table></figure>

<p>做完了这些数据整合后，把渲染视图的任务再次交给子类。</p>
<h3 id="6-6-FreeMarkerView-分析"><a href="#6-6-FreeMarkerView-分析" class="headerlink" title="6.6 FreeMarkerView 分析"></a>6.6 FreeMarkerView 分析</h3><p>我们在开发中一般会使用的视图解析器有各种模板引擎或者jsp等等，在 AbstractUrlBasedView 和 AbstractTemplateView中，分别处理好了url和model，接下来就该真正的视图工作了。这里我们试着分析一下 FreeMarkerView，其他的模板引擎工作原理也差不多。</p>
<h4 id="6-6-1-FreeMarkerView-初始化分析"><a href="#6-6-1-FreeMarkerView-初始化分析" class="headerlink" title="6.6.1 FreeMarkerView 初始化分析"></a>6.6.1 FreeMarkerView 初始化分析</h4><p>FreeMarkerView 初始化会从web应用上下文中加载相关配置。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Invoked on startup. Looks for a single FreeMarkerConfig bean to</span></span><br><span class="line"><span class="comment"> * find the relevant Configuration for this factory.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Checks that the template for the default Locale can be found:</span></span><br><span class="line"><span class="comment"> * FreeMarker will check non-Locale-specific templates if a</span></span><br><span class="line"><span class="comment"> * locale-specific one is not found.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> freemarker.cache.TemplateCache#getTemplate</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initServletContext</span><span class="params">(ServletContext servletContext)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (getConfiguration() != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.taglibFactory = <span class="keyword">new</span> TaglibFactory(servletContext);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        FreeMarkerConfig config = autodetectConfiguration();</span><br><span class="line">        setConfiguration(config.getConfiguration());</span><br><span class="line">        <span class="keyword">this</span>.taglibFactory = config.getTaglibFactory();</span><br><span class="line">    &#125;</span><br><span class="line">    GenericServlet servlet = <span class="keyword">new</span> GenericServletAdapter();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        servlet.init(<span class="keyword">new</span> DelegatingServletConfig());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (ServletException ex) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> BeanInitializationException(<span class="string">"Initialization of GenericServlet adapter failed"</span>, ex);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">this</span>.servletContextHashModel = <span class="keyword">new</span> ServletContextHashModel(servlet, getObjectWrapper());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Autodetect a &#123;<span class="doctag">@link</span> FreeMarkerConfig&#125; object via the ApplicationContext.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the Configuration instance to use for FreeMarkerViews</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> BeansException if no Configuration instance could be found</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #getApplicationContext</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #setConfiguration</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> FreeMarkerConfig <span class="title">autodetectConfiguration</span><span class="params">()</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> BeanFactoryUtils.beanOfTypeIncludingAncestors(</span><br><span class="line">                getApplicationContext(), FreeMarkerConfig<span class="class">.<span class="keyword">class</span>, <span class="title">true</span>, <span class="title">false</span>)</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (NoSuchBeanDefinitionException ex) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ApplicationContextException(</span><br><span class="line">                <span class="string">"Must define a single FreeMarkerConfig bean in this web application context "</span> +</span><br><span class="line">                <span class="string">"(may be inherited): FreeMarkerConfigurer is the usual implementation. "</span> +</span><br><span class="line">                <span class="string">"This bean may be given any name."</span>, ex);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个 FreeMarkerConfig 类就是需要我们在xml中配置的FreeMarker配置对象，其中可能有模板路径，文件字符格式等等。</p>
<h4 id="6-6-2-FreeMarkerView-处理请求分析"><a href="#6-6-2-FreeMarkerView-处理请求分析" class="headerlink" title="6.6.2 FreeMarkerView 处理请求分析"></a>6.6.2 FreeMarkerView 处理请求分析</h4><p>之前讲到 UrlBasedViewResolver 在loadView方法中会调用 AbstractUrlBasedView 的checkResource方法判断资源是否存在。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Check that the FreeMarker template used for this view exists and is valid.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Can be overridden to customize the behavior, for example in case of</span></span><br><span class="line"><span class="comment"> * multiple templates to be rendered into a single view.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">checkResource</span><span class="params">(Locale locale)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// Check that we can get the template, even if we might subsequently get it again.</span></span><br><span class="line">        getTemplate(getUrl(), locale);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (FileNotFoundException ex) &#123;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"No FreeMarker view found for URL: "</span> + getUrl());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (ParseException ex) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ApplicationContextException(</span><br><span class="line">                <span class="string">"Failed to parse FreeMarker template for URL ["</span> +  getUrl() + <span class="string">"]"</span>, ex);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (IOException ex) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ApplicationContextException(</span><br><span class="line">                <span class="string">"Could not load FreeMarker template for URL ["</span> + getUrl() + <span class="string">"]"</span>, ex);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>而最终的实现就是判断是否能获得相关模板文件，如果能获得就返回true。</p>
<p>当确认能够渲染后，最终会调用renderMergedTemplateModel方法进行最终的渲染，该方法又会调用doRender方法执行真正的渲染，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Process the model map by merging it with the FreeMarker template.</span></span><br><span class="line"><span class="comment"> * Output is directed to the servlet response.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;This method can be overridden if custom behavior is needed.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">renderMergedTemplateModel</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        Map&lt;String, Object&gt; model, HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    exposeHelpers(model, request);</span><br><span class="line">    doRender(model, request, response);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Render the FreeMarker view to the given response, using the given model</span></span><br><span class="line"><span class="comment"> * map which contains the complete template model to use.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;The default implementation renders the template specified by the "url"</span></span><br><span class="line"><span class="comment"> * bean property, retrieved via &#123;<span class="doctag">@code</span> getTemplate&#125;. It delegates to the</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@code</span> processTemplate&#125; method to merge the template instance with</span></span><br><span class="line"><span class="comment"> * the given template model.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Adds the standard Freemarker hash models to the model: request parameters,</span></span><br><span class="line"><span class="comment"> * request, session and application (ServletContext), as well as the JSP tag</span></span><br><span class="line"><span class="comment"> * library hash model.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Can be overridden to customize the behavior, for example to render</span></span><br><span class="line"><span class="comment"> * multiple templates into a single view.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> model the model to use for rendering</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> response current servlet response</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> IOException if the template file could not be retrieved</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception if rendering failed</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #setUrl</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.web.servlet.support.RequestContextUtils#getLocale</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #getTemplate(java.util.Locale)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #processTemplate</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> freemarker.ext.servlet.FreemarkerServlet</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doRender</span><span class="params">(Map&lt;String, Object&gt; model, HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// Expose model to JSP tags (as request attributes).</span></span><br><span class="line">    exposeModelAsRequestAttributes(model, request);</span><br><span class="line">    <span class="comment">// Expose all standard FreeMarker hash models.</span></span><br><span class="line">    SimpleHash fmModel = buildTemplateModel(model, request, response);</span><br><span class="line">    <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">        logger.debug(<span class="string">"Rendering FreeMarker template ["</span> + getUrl() + <span class="string">"] in FreeMarkerView '"</span> + getBeanName() + <span class="string">"'"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Grab the locale-specific version of the template.</span></span><br><span class="line">    Locale locale = RequestContextUtils.getLocale(request);</span><br><span class="line">    processTemplate(getTemplate(locale), fmModel, response);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Process the FreeMarker template to the servlet response.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Can be overridden to customize the behavior.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> template the template to process</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> model the model for the template</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> response servlet response (use this to get the OutputStream or Writer)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> IOException if the template file could not be retrieved</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> TemplateException if thrown by FreeMarker</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> freemarker.template.Template#process(Object, java.io.Writer)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">processTemplate</span><span class="params">(Template template, SimpleHash model, HttpServletResponse response)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> IOException, TemplateException </span>&#123;</span><br><span class="line">    template.process(model, response.getWriter());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="6-7-小结"><a href="#6-7-小结" class="headerlink" title="6.7 小结"></a>6.7 小结</h3><p>View接口相比较而言还算简单，但其中门门还真不少，谁能想到 ViewResolver 竟然需要调用 AbstractUrlBasedView 的checkResource方法判断这个View是否能渲染数据。AbstractUrlBasedView 使得View的获取从通过beanName的方式转换为通过View自身的判断，真是一个神转折。</p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Gavin Zhang
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-4/" title="SpringMVC 解毒4">http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-4/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/springmvc/" rel="tag"># springmvc</a>
          
            <a href="/tags/spring/" rel="tag"># spring</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/12/learn-springmvc-code-3/" rel="next" title="SpringMVC 解毒3">
                <i class="fa fa-chevron-left"></i> SpringMVC 解毒3
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/12/learn-springmvc-code-chart/" rel="prev" title="SpringMVC类图关系">
                SpringMVC类图关系 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://avatars3.githubusercontent.com/u/5567916" alt="Gavin Zhang">
            
              <p class="site-author-name" itemprop="name">Gavin Zhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">129</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">158</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/jiangmitiao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:me at gavinzh.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#5-ViewResolver"><span class="nav-number">1.</span> <span class="nav-text">5 ViewResolver</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1-BeanNameViewResolver-分析"><span class="nav-number">1.1.</span> <span class="nav-text">5.1 BeanNameViewResolver 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-ViewResolverComposite-分析"><span class="nav-number">1.2.</span> <span class="nav-text">5.2 ViewResolverComposite 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3-ContentNegotiatingViewResolver-分析"><span class="nav-number">1.3.</span> <span class="nav-text">5.3 ContentNegotiatingViewResolver 分析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-3-1-ContentNegotiatingViewResolver-初始化分析"><span class="nav-number">1.3.1.</span> <span class="nav-text">5.3.1 ContentNegotiatingViewResolver 初始化分析</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3-2-ContentNegotiatingViewResolver-处理请求分析"><span class="nav-number">1.4.</span> <span class="nav-text">5.3.2 ContentNegotiatingViewResolver 处理请求分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-4-AbstractCachingViewResolver-分析"><span class="nav-number">1.5.</span> <span class="nav-text">5.4 AbstractCachingViewResolver 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-5-XmlViewResolver-分析"><span class="nav-number">1.6.</span> <span class="nav-text">5.5 XmlViewResolver 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-6-ResourceBundleViewResolver-分析"><span class="nav-number">1.7.</span> <span class="nav-text">5.6 ResourceBundleViewResolver 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-7-UrlBasedViewResolver-分析"><span class="nav-number">1.8.</span> <span class="nav-text">5.7 UrlBasedViewResolver 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-8-InternalResourceViewResolver-分析"><span class="nav-number">1.9.</span> <span class="nav-text">5.8 InternalResourceViewResolver 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-9-AbstractTemplateViewResolver-分析"><span class="nav-number">1.10.</span> <span class="nav-text">5.9 AbstractTemplateViewResolver 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-10-FreeMarkerViewResolver-分析"><span class="nav-number">1.11.</span> <span class="nav-text">5.10 FreeMarkerViewResolver 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-11-小结"><span class="nav-number">1.12.</span> <span class="nav-text">5.11 小结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-View"><span class="nav-number">2.</span> <span class="nav-text">6 View</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#6-1-AbstractView-分析"><span class="nav-number">2.1.</span> <span class="nav-text">6.1 AbstractView 分析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#6-1-1-AbstractView-初始化分析"><span class="nav-number">2.1.1.</span> <span class="nav-text">6.1.1 AbstractView 初始化分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-1-2-AbstractView-处理请求分析"><span class="nav-number">2.1.2.</span> <span class="nav-text">6.1.2 AbstractView 处理请求分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-1-3-AbstractView-其他"><span class="nav-number">2.1.3.</span> <span class="nav-text">6.1.3 AbstractView 其他</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-2-AbstractUrlBasedView-分析"><span class="nav-number">2.2.</span> <span class="nav-text">6.2 AbstractUrlBasedView 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-3-InternalResourceView-和-JstlView"><span class="nav-number">2.3.</span> <span class="nav-text">6.3 InternalResourceView 和 JstlView</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-4-RedirectView-分析"><span class="nav-number">2.4.</span> <span class="nav-text">6.4 RedirectView 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-5-AbstractTemplateView-分析"><span class="nav-number">2.5.</span> <span class="nav-text">6.5 AbstractTemplateView 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-6-FreeMarkerView-分析"><span class="nav-number">2.6.</span> <span class="nav-text">6.6 FreeMarkerView 分析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#6-6-1-FreeMarkerView-初始化分析"><span class="nav-number">2.6.1.</span> <span class="nav-text">6.6.1 FreeMarkerView 初始化分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-6-2-FreeMarkerView-处理请求分析"><span class="nav-number">2.6.2.</span> <span class="nav-text">6.6.2 FreeMarkerView 处理请求分析</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-7-小结"><span class="nav-number">2.7.</span> <span class="nav-text">6.7 小结</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2013 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gavin Zhang</span>

  

  
</div>





<div>
	<a href="http://www.beian.miit.gov.cn/" target="_blank">陕ICP备17010002号-1</a>
</div>





        




  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=61868582";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1261805793&web_id=1261805793" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>





  



  






  













  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fastclick/1.0.6/fastclick.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.0"></script>



  


  

    
      <script id="dsq-count-scr" src="https://zhang-hengs-website-blog.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-4/';
          this.page.identifier = '2018/08/12/learn-springmvc-code-4/';
          this.page.title = 'SpringMVC 解毒4';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://zhang-hengs-website-blog.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("EhAMmIXTRGtethTcgYwA9afH-gzGzoHsz", "jzP1TaBhMleAUgPLXyB0h8oQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=6.0.0"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=6.0.0"></script>


  

</body>
</html>
